<?php
if ( ! defined('__TYPECHO_ROOT_DIR__'))
{
    exit;
}
/**
 *认证模块
 *页面上采用ajax方式请求,返回格式:
 *code-msg
 *code值:
 *1 正确
 *2 缺少frob参数
 *3 获取autoToken出错
 *4 数据库出错
 */
$frob = $_GET['frob'];

if ( ! $frob)
{
    exit('2-缺少frob参数');
}
include 'Tyupoo.php';

$pluginOptions = $options->plugin('Tyupoo');
$typ = new Tyupoo($pluginOptions->apiKey, $pluginOptions->sharedSecret, '');
$info = $typ->getTokenInfo($frob); 
if ( ! empty($info['err']))
{
    $code = $typ->getErrCode($info);
    $msg  = $typ->getErrMsg($info);
    exit("3-{$code}:{$msg}");
}
$token    = $info['auth']['token'];
$userInfo = $info['auth']['user']['@attributes'];
$userID   = $userInfo['id'];
/**
 *id
 *nickname
 *username
 */
$saveOptions = array(
    'apiKey'       => $pluginOptions->apiKey,
    'sharedSecret' => $pluginOptions->sharedSecret,
    'authToken'    => $token,
    'userID'       => $userID,
    'pluginVer'    => $pluginOptions->pluginVer,
    //'albumId'     => $albumId,
);

$Typecho_Db = Typecho_Db::get();

$ret = $Typecho_Db->query( $Typecho_Db->update('table.options')
    ->rows(array('value' => serialize($saveOptions)))
    ->where('name = ?', 'plugin:Tyupoo')
);
if ( ! $ret)
{
    exit('4-数据库出错');
}
echo '1-ok';
?>